package io.renren.modules.sp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.common.constant.Constant;
import io.renren.common.utils.*;
import io.renren.modules.sp.dao.SpMatchDao;
import io.renren.modules.sp.dao.SpMatchItemDao;
import io.renren.modules.sp.dao.SpMatchItemTeamDao;
import io.renren.modules.sp.dao.SpMatchItemTeamUserDao;
import io.renren.modules.sp.dto.SpMatchItemDTO;
import io.renren.modules.sp.entity.*;
import io.renren.modules.sp.service.MainIndividualService;
import io.renren.modules.sp.service.SpMatchItemService;
import io.renren.modules.security.user.SecurityUser;
import io.renren.modules.sys.dao.SysCommDao;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

/**
 * 赛项
 *
 * @author whc 15953295779@126.com
 * @since 3.0 2023-04-20
 */
@Service
public class SpMatchItemServiceImpl extends CrudServiceImpl<SpMatchItemDao, SpMatchItemEntity, SpMatchItemDTO> implements SpMatchItemService {

    @Autowired
    private SysCommDao commDao;
    @Autowired
    private SpMatchDao spMatchDao;
    @Autowired
    private SpMatchItemTeamDao spMatchItemTeamDao;

    @Autowired
    private MainIndividualService mainIndividualService;
    @Autowired
    private SpMatchItemTeamUserDao spMatchItemTeamUserDao;

    @Override
    public QueryWrapper<SpMatchItemEntity> getWrapper(Map<String, Object> params){
        QueryWrapper<SpMatchItemEntity> wrapper = new QueryWrapper<>();

        Integer id = (Integer)params.get("id");
        wrapper.eq(id!=null, "id", id);
        String matchId = (String)params.get("matchId");
        wrapper.eq(StringUtils.isNotBlank(matchId), "match_id", matchId);
        Long adminId = (Long)params.get("adminId");
        wrapper.eq(adminId!=null, "admin_id", adminId);

        return wrapper;
    }

    @Override
    @Transactional
    public void updateMatchItem(SpMatchItemDTO dto){
        SpMatchItemEntity entity = ConvertUtils.sourceToTarget(dto, SpMatchItemEntity.class);
        if(entity.getAdminId() == null){
            entity.setAdminId(null);
        }
        this.baseDao.updateById(entity);
        //获取赛事id
        Long matchId = dto.getMatchId();
        //修改赛事的admin_item_id字段
        SpMatchEntity spMatchEntity = spMatchDao.selectById(matchId);
        spMatchEntity.setAdminItemId(dto.getAdminId());
        spMatchDao.updateById(spMatchEntity);
    }

    @Override
    public Map<String,Object> itemTotal(Long matchItemId,String type){
        return this.baseDao.itemTotal(matchItemId,type);
    }

    @Override
    public Map<String,Object> itemEntryTotal(Long matchId,Long matchItemId,String type) {
        return this.baseDao.itemEntryTotal(matchId, matchItemId, type);
    }

    @Override
    public Map<String,Object> queryBymatchItemId(Long matchItemId){
        return this.baseDao.queryBymatchItemId(matchItemId);
    }

    @Override
    public void updateNotice(SpMatchItemDTO dto) {
        SpMatchItemEntity entity = this.baseDao.selectById(dto.getId());
        entity.setNoticeTitle(dto.getNoticeTitle());
        entity.setNoticeContent(dto.getNoticeContent());
        entity.setNoticeTime(new Date());
        this.baseDao.updateById(entity);
        //清空日志
        Map<String, Object> param = new HashMap();
        String sql = "DELETE from sp_notice_item_log  t where t.item_id = #{p.id}";
        param.put("id",dto.getId());
        commDao.delete(sql, param);
    }

    /**
     * 开放抽签，先把顺序生成好
     * 1、查询赛项下所有的group
     * 2、每个group打算顺序
     *
     */
    @Override
    public Result openDraw(Long matchItemId){
        //小学组、初中组、高中组
        //100301、100302、100303
        Result result = this.pubDraw(matchItemId, 100301);
        result = this.pubDraw(matchItemId, 100302);
        result = this.pubDraw(matchItemId, 100303);
        return result;
    }

    /**
     * 公布抽签结果
     * 1、查询赛项下所有的group
     * 2、每个group打算顺序
     *
     */
    private Result pubDraw(Long matchItemId, Integer groupId){
        //小学组、初中组、高中组
        //100301、100302、100303
        List<SpMatchItemTeamEntity> list = spMatchItemTeamDao.selectList(new QueryWrapper<SpMatchItemTeamEntity>()
                .eq("match_item_id",matchItemId)
                .eq("group_id", groupId)
                .in("status", 1,2,4,5,6)
        );
        if(list==null || list.size()==0){
            return new Result().error("没有参赛队");
        }

        //把所有参赛队的序号放入一个集合
        List<Integer> sorts = new ArrayList<>();
        for (int i=0; i<list.size(); i++){
            sorts.add(i+1);
        }

        //打乱sorts的顺序
        Collections.shuffle(sorts);

        for(SpMatchItemTeamEntity teamEntity : list){
            if(sorts.size()==0){
                return new Result().error("序号不够");
            }
            teamEntity.setSortPre(sorts.get(0));
            this.spMatchItemTeamDao.updateById(teamEntity);
            sorts.removeIf(o->o==sorts.get(0));
        }
        return new Result().ok("");
    }

    //同步数据
    @Override
    public void syncData(){
        List<Map<String, Object>> list = mainIndividualService.queryMainIndividual();
        Integer score = 0;
        BigDecimal score1 = new BigDecimal(0);
        // 修改分数
        for (Map<String, Object> map : list){
            Map<String, Object>  user = spMatchItemTeamUserDao.queryUserByTicket((String) map.get("stu_no"));
            //修改
            if(user!=null) {
                SpMatchItemTeamUserEntity entity = new SpMatchItemTeamUserEntity();
                entity.setId((Long) user.get("id"));
                score = (Integer) map.get("score");
                score1 = (BigDecimal) map.get("duration");
                entity.setScore(score.toString());
                entity.setScore1(score1.toString());
                spMatchItemTeamUserDao.updateById(entity);
                System.out.println(map.get("stu_no") + " " + score + " " + score1);
            }
        }
    }

    // 显示隐藏成绩
    @Override
    public void scoreOpen(Long id) {
        SpMatchItemEntity entity = this.baseDao.selectById(id);
        if(entity.getScoreOpen() == null){
            entity.setScoreOpen(0);
        }
        if (entity.getScoreOpen() == 1) {
            entity.setScoreOpen(0);
        } else {
            entity.setScoreOpen(1);
        }
        this.baseDao.updateById(entity);
    }

    // 删除赛项
    @Override
    public Result deleteItem(Long[] ids) {
        //判断是否有报名记录,有报名记录不能删除
        boolean flag = false;
        for (Long id : ids) {
            //判断是否有报名记录
            List<SpMatchItemTeamEntity> list = spMatchItemTeamDao.selectList(new QueryWrapper<SpMatchItemTeamEntity>()
                    .eq("match_item_id",id)
            );
            if(list!=null && list.size()>0){
                flag = true;
                break;
            }
        }
        if(flag){
            return new Result().error("存在报名记录，不能删除");
        }else{
            //删除赛项
            for (Long id : ids) {
                this.baseDao.deleteById(id);
            }
        }
        return new Result().ok("成功");
    }

    /**
     * 下载选手、老师图片
     *
     * @param
     * @param response
     * @throws Exception
     */
    @Override
    public Result<String> downloadHeaderFile(Map<String, Object> params, HttpServletResponse response) throws Exception {
        String type = (String)params.get("type");
        Long matchItemId = Long.parseLong((String)params.get("matchItemId"));
        List<Map<String,Object>> list = this.baseDao.queryUserHeader(type, matchItemId);
        //list移除集合中entryPic字段等于空的数据
        List<Map<String, Object>> urlList = new ArrayList<>();
        //把list中的entryPic字段不为空的取出来放到urlList中
        Map<String, Object> urlMap = null;
        for (Map<String, Object> map : list) {
            urlMap = new HashMap<>();
            urlMap.put("url", map.get("header"));
            urlMap.put("ticket", map.get("real_name") +"-"+ map.get("ticket") );
            urlList.add(urlMap);
        }
        if(list.size()>0) {
            //清空输出流
            response.reset();
            //定义输出类型
            response.setContentType("application/octet-stream");
            Map<String,Object> map = list.get(0);
            // 赛事+筛选条件+参赛证/号码布+月日.zip
            String matchName = (String)map.get("match_name");
            String itemName = (String)map.get("item_name");
            //[赛事名]-[赛项名]-[下载日期]-参赛照片.zip
            String title = matchName + "-" + itemName +"-"+ DateUtils.format(new Date(),"MMdd")+ "-参赛照片.zip";
            // 编译成utf-8格式
            title = URLEncoder.encode(title,"UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + title + ";" + "filename*=utf-8''" + title);
            // 打包下载
            ZipUtils.getZipFile(IOUtils.getByte(urlList), response.getOutputStream(), response);
            return new Result<String>().ok("下载成功");
        }else {
            return new Result<String>().error("没有可下载的数据");
        }
    }

    @Override
    public List<SpMatchItemEntity> listBy(QueryWrapper<SpMatchItemEntity> wrapper) {
        return this.baseDao.selectList(wrapper);
    }




}
